package tugowar.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import tugowar.models.Player;

public class ScoreManager {
	
	static ScoreBoard scoreboard;
	private static Timer scoreUpdateInterval;
	
	private static int teamSwitch = 0;
	
	
	
	public ScoreManager(){
		
		if(ScoreManager.scoreboard == null)
			ScoreManager.scoreboard = new ScoreBoard();
		
		if(ScoreManager.scoreUpdateInterval == null){
			ScoreManager.scoreUpdateInterval = new Timer();
			ScoreManager.scoreUpdateInterval.scheduleAtFixedRate(new UpdateScoreTask(), 0, 100);
		}
		
		
	}
	
	public int register(String name) throws Error{
		int teamSwitch = ScoreManager.teamSwitch = (ScoreManager.teamSwitch == 0) ? 1 : 0;
		
		Player player = new Player(name);
		
		if(teamSwitch == 1){
			scoreboard.rightPlayers.add(player);
			scoreboard.rightPlayerMap.put(player.name, player);
		}else{
			scoreboard.leftPlayers.add(player);
			scoreboard.leftPlayerMap.put(player.name, player);
		}
		
		return teamSwitch;
	}
	
	
	
	public void score(String name) throws Error{
		if(scoreboard.leftPlayerMap.containsKey(name))
			scoreboard.leftPlayerMap.get(name).score++;
		else if(scoreboard.rightPlayerMap.containsKey(name))
			scoreboard.rightPlayerMap.get(name).score++;
	}
	
	
	
	public int getScore(){
		return scoreboard.score;
	}
	
}




class ScoreBoard{
	
	public int score;
	public List<Player> leftPlayers;
	public List<Player> rightPlayers;
	
	public Map<String, Player> leftPlayerMap;
	public Map<String, Player> rightPlayerMap;
	
	
	public ScoreBoard(){
		score = 0;
		leftPlayers = new ArrayList<Player>();
		rightPlayers = new ArrayList<Player>();
		leftPlayerMap = new HashMap<String, Player>();
		rightPlayerMap = new HashMap<String, Player>();
	}	
}





class UpdateScoreTask extends TimerTask{
	
	
	
	public void run(){
		int leftScore = 0;
		int rightScore = 0;
		
		for(Iterator<Player> leftPlayers = ScoreManager.scoreboard.leftPlayers.iterator(); leftPlayers.hasNext();){
			leftScore += leftPlayers.next().score;
		}
		
		for(Iterator<Player> rightPlayers = ScoreManager.scoreboard.rightPlayers.iterator(); rightPlayers.hasNext();){
			rightScore += rightPlayers.next().score;
		}
		
		ScoreManager.scoreboard.score = rightScore - leftScore;
	}
}
